package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 切面：增强目标方法的类
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 定义拦截的切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}
    /**
     * 定义前置通知
     *joinpiont:拦截到的目标方法分装的对象
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行自动填充...");
        Object[] args = joinPoint.getArgs();
        if(args==null||args.length==0){
            return;
        }
        try {
            //获取目标方法中的参数
            Object object = args[0];
            //方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取方法
            Method method = signature.getMethod();
            //获取方法上的注解 @AutoFill(value = OperationType.INSERT)
            AutoFill autoFill = method.getAnnotation(AutoFill.class);
            //获取注解上的值
            OperationType operationType = autoFill.value();
            //反射填充四个字段，createTime,updateTime,createUser,updateUser
            Class<?> clazz = object.getClass();

            //反射填充两个字段，updateTime,updateUser
            Method setUpdateTime = clazz.getMethod("setUpdateTime", LocalDateTime.class);
            setUpdateTime.invoke(object, LocalDateTime.now());

            Method setUpdateUser = clazz.getMethod("setUpdateUser", Long.class);
            setUpdateUser.invoke(object, BaseContext.getCurrentId());

            //判断对数据库的操作是不是Insert
            if(operationType == OperationType.INSERT){

                //获取字节中的setCreateTime方法
                Method setCreateTime = clazz.getMethod("setCreateTime", LocalDateTime.class);
                //调用setCreateTime方法
                setCreateTime.invoke(object, LocalDateTime.now());

                Method setCreateUser = clazz.getMethod("setCreateUser", Long.class);
                setCreateUser.invoke(object, BaseContext.getCurrentId());
            }
        }catch (Exception e){
            log.error("自动填充失败：{}",e.getMessage());
        }





    }
}
